from weibosender.db.sql_helper import SqlHelper


class SendersDAL:

    _sql_login_senders = 'select id,login_name,password,uid,cookies from senders;'
    _sql_get_senders = 'select a.id,a.login_name,a.password,a.uid,a.cookies,a.st,a.created,a.updated from senders a \
                        left join (select id,uid from senders_limit_log where date(created) is date(\'now\', \'localtime\')) b \
                        on a.uid = b.uid \
                        where a.uid is not null and a.cookies is not null and b.id is null;'
    _sql_logged = 'select count(0) from senders where uid not null and cookies not null;'
    _sql_update = 'update senders set uid=(?),cookies=(?),updated=(?) where id=(?);'
    _sql_update_st = 'update senders set st=(?),updated=(?) where id=(?);'

    @staticmethod
    def get_login_senders():
        return SqlHelper.fetchall(SendersDAL._sql_login_senders)

    @staticmethod
    def get_senders():
        return SqlHelper.fetchall(SendersDAL._sql_get_senders)

    # 获取已登录用户
    @staticmethod
    def get_logged():
        result = SqlHelper.fetchone(SendersDAL._sql_logged)
        if not result or len(result) == 0:
            return 0
        return result[0]

    @staticmethod
    def update(user):
        return SqlHelper.execute(SendersDAL._sql_update, user)

    @staticmethod
    def update_st(user):
        return SqlHelper.execute(SendersDAL._sql_update_st, user)